package org.pine.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;

import java.util.Objects;

/**
 * redis缓存
 *
 * @author pine manage
 * @since 2024-08-13
 */
@Slf4j
public class RedisCache {

    private final CacheManager redissonCacheManager;

    public RedisCache(CacheManager redissonCacheManager) {
        this.redissonCacheManager = redissonCacheManager;
    }


    /**
     * 获取缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     * @return 缓存数据
     */
    public Object get(String cacheName, String key) {
        log.info("RedisCache获取缓存，cacheName={}, key={}", cacheName, key);
        Cache cache = redissonCacheManager.getCache(cacheName);
        if (Objects.isNull(cache)) {
            return null;
        }

        // 从缓存中获取数据
        return cache.get(key);
    }

    /**
     * 设置缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     * @param value     缓存数据
     */
    public void set(String cacheName, String key, Object value) {
        log.info("RedisCache设置缓存，cacheName={}, key={}, value={}", cacheName, key, value);
        Cache cache = redissonCacheManager.getCache(cacheName);
        if (Objects.isNull(cache)) {
            return;
        }

        // 将数据放入缓存
        cache.put(key, value);
    }

    /**
     * 移除缓存
     *
     * @param cacheName 缓存名称
     * @param key       缓存key
     */
    public void remove(String cacheName, String key) {
        log.info("RedisCache移除缓存，cacheName={}, key={}", cacheName, key);
        Cache cache = redissonCacheManager.getCache(cacheName);
        if (Objects.isNull(cache)) {
            return;
        }

        // 从缓存中移除数据
        cache.evict(key);
    }

    /**
     * 移除所有缓存
     *
     * @param cacheName 缓存名称
     */
    public void removeAll(String cacheName) {
        log.info("RedisCache移除所有缓存，cacheName={}", cacheName);
        Cache cache = redissonCacheManager.getCache(cacheName);
        if (Objects.isNull(cache)) {
            return;
        }

        // 从缓存中移除数据
        cache.clear();
    }
}
